package com.woyou.ui.activity;

import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.citaq.ideliver.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMSocialService;
import com.woyou.Constant;
import com.woyou.bean.CodeResult;
import com.woyou.bean.Info;
import com.woyou.bean.MyOrderItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.CheckUpdateReq;
import com.woyou.bean.rpc.CheckUpdateRes;
import com.woyou.service.NetWorkCenter;
import com.woyou.service.receiver.JPushReceiver_;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.ui.activity.orderlist.MyOrderActivity;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.component.CheckUpdateDialog;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.fragment.IndexFragment_;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.utils.DeviceUtils;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.ShareUtils;

/**
 * 广告页面
 * 
 * @author zhou.ni
 *
 */
@EActivity(R.layout.fm_activites)
public class ActivitiesActivity extends BaseActivity implements IBackEventStrategy, OnClickListener {

	private static final String TAG = "ActivitiesFragment";

	@ViewById(R.id.act_container)
	FrameLayout mContainer;
	@ViewById(R.id.back)
	RelativeLayout back;
	@ViewById(R.id.head_title)
	TextView headTitle;
	@ViewById(R.id.collection)
	RelativeLayout collection;
	@ViewById(R.id.collection_iv)
	ImageView collection_iv;
	@ViewById(R.id.hintView)
	ErrorHintView hintView;

	private InputMethodManager imm; // 软键盘
	private MyLocationListener mListener;
	private BDLocation mlocation;
	private String url = "";
	private WebView mWeb;
	private String affertName; // 从哪个界面传过来

	@AfterViews
	public void init() {
		initView();
		mListener = new MyLocationListener();
		mBaiduLocationService.registerLocationListenner(mListener);
		mBaiduLocationService.startLocation();
		obtainInfo();
	}

	class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mBaiduLocationService.stop();
			mBaiduLocationService.unRegisterLocationListener(mListener);
			Log.i("onReceiveLocation", "onPageFinished");
			dismissProgressDialog();
			if (location != null) {
				mlocation = location;
			}
		}

	}

	/**
	 * 返回上一个Fragment
	 */
	@Click(R.id.back)
	void back() {
		backOperate();
	}

	public void initView() {
		if (mContainer != null)
			mContainer.removeAllViews();

		imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

		LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		if (mWeb == null) {
			mWeb = new WebView(mContext);
		}
		mContainer.addView(mWeb, layoutParams);

		initWebView(url);
		headTitle.setText("返回首页");
		collection_iv.setImageResource(R.raw.icon_more);
		collection.setVisibility(View.VISIBLE);
		collection.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.collection:
			openActivityDialog(mActivity);
			break;
		}
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(String url) {
		try {
			// 如果访问的页面中有Javascript，则webview必须设置支持Javascript。
			mWeb.getSettings().setJavaScriptEnabled(true);
			mWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
			// 触摸焦点起作用
			mWeb.requestFocus();
			// 取消滚动条
			mWeb.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
			// 设置WevView要显示的网页：
			mWeb.loadUrl(url);
			// 设置不可缩放
			mWeb.getSettings().setSupportZoom(false);
			mWeb.getSettings().setBuiltInZoomControls(false);

			mWeb.setWebViewClient(new MyWebViewClient());
			mWeb.setWebChromeClient(new WebChromeClient());
			mWeb.addJavascriptInterface(this, "ideliver");
		} catch (Exception e) {
			Toast.makeText(mContext, "加载出错", Toast.LENGTH_SHORT).show();
		}

	}

	class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (!TextUtils.isEmpty(url)) {
				mWeb.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {

			hintView.hideLoading();

			String title = view.getTitle();
			if (TextUtils.isEmpty(title)) {
				return;
			}

			if (!title.contains("ideliver")) {
				if (!NetWorkCenter.isNetworkConnected(mContext)) {
					hintView.netError(new OperateListener() {

						@Override
						public void operate() {
							initView();
						}
					});
				} else {
					hintView.loadFailure(new OperateListener() {

						@Override
						public void operate() {
							initView();
						}
					});
				}

			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			if (NetWorkCenter.isNetworkConnected(mContext)) {
				hintView.loadFailure(new OperateListener() {

					@Override
					public void operate() {
						initView();
					}
				});
			} else {
				hintView.netError(new OperateListener() {

					@Override
					public void operate() {
						initView();
					}
				});
			}
			mWeb.addJavascriptInterface(ActivitiesActivity.this, "ideliver");
		}
	}

	/**
	 * 打开分享活动的dialog
	 * 
	 * @param context
	 */
	public void openActivityDialog(Context context) {
		final Dialog dialog = new Dialog(context, R.style.defaultDialogStyle);
		Window dialogWindow = dialog.getWindow();
		dialogWindow.setGravity(Gravity.BOTTOM);
		// 设置dialog平铺
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(0, 0, 0, 0);
		WindowManager.LayoutParams lp = win.getAttributes();
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		win.setAttributes(lp);

		View view = LayoutInflater.from(context).inflate(R.layout.custom_activity, null);
		TextView refresh = (TextView) view.findViewById(R.id.activity_refresh);
		TextView share = (TextView) view.findViewById(R.id.activity_share);
		TextView browser = (TextView) view.findViewById(R.id.activity_browser);
		TextView cancel = (TextView) view.findViewById(R.id.activity_cancel);

		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();

		refresh.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mWeb.reload();
				mWeb.scrollTo(0, 0);
				dialog.dismiss();
			}
		});
		share.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ShareUtils shareUtils = ShareUtils.getInstance(mActivity);
				UMSocialService mController = shareUtils.getmController();
				url = resetUrl(url);
				shareUtils.setActivityContent(url);
				mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ,
						SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA);
				mController.openShare(mActivity, false);
				dialog.dismiss();
			}
		});
		browser.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse(url);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
				dialog.dismiss();
			}
		});
		cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

	}

	/**
	 * JS端发送消息到android
	 * 
	 * @param message
	 */
	@SuppressWarnings("rawtypes")
	public void messageFromJS(String message) {
		UserInfo userInfo = mUserModel.getUserInfo();
		Log.i(TAG, "messageFromJS");
		// Toast.makeText(mContext, message, 1).show();

		try {
			JSONObject msg = new JSONObject(message);
			String type = msg.getString("messageType");
			if ("orderList".equals(type)) {
				// 查看订单列表
				openActivity(MyOrderActivity.class, null);

			} else if ("orderDetails".equals(type)) {
				// 查看订单详情
				String params = msg.getString("params");
				JSONObject jsonObject = new JSONObject(params);
				String oId = jsonObject.getString("oId");
				MyOrderItem order = new MyOrderItem();
				order.setoId(oId);
				Info<MyOrderItem> info = new Info<MyOrderItem>(order);
				info.setOrigin(ActivitiesActivity_.class);
				openActivity(OrderDetailActivity.class, info);

			} else if ("feedback".equals(type)) {
				// 跳转到用户反馈界面消息
				openActivity(AppProblemActivity_.class, null);

			} else if ("tryAgain".equals(type)) {
				showProgressDialog();
				mBaiduLocationService.registerLocationListenner(mListener);
				mBaiduLocationService.startLocation();
				
			} else if ("browseShops".equals(type)) {
				Info<Class> info = new Info<Class>(ShopsFragment_.class);
				info.setOrigin(ActivitiesActivity_.class);
				openActivity(HomeActivity_.class, info);
				
			} else if ("browseShops2".equals(type)) {

			} else if ("selectAd".equals(type)) {
				String params = msg.getString("params");
				JSONObject jsonObject = new JSONObject(params);
				String webUrl = jsonObject.getString("AdUrl");
				String list = jsonObject.getString("codeList");
				if (!TextUtils.isEmpty(webUrl) && URLUtil.isHttpUrl(webUrl)) {
					webUrl = webUrl + "/stPhone=" + userInfo.getPhone() + "/stLng=" + mlocation.getLongitude()
							+ "/stLat=" + mlocation.getLatitude() + "/platform=android" + "/version="
							+ GetVersion(mContext);
					Info<String> inf = new Info<String>(webUrl);
					openActivity( ActivitiesActivity_.class, inf);

				} else if (!TextUtils.isEmpty(list)) {
					Gson gson = new Gson();
					List<String> codeList = gson.fromJson(list, new TypeToken<List<String>>() {
					}.getType());
					if (codeList != null && codeList.size() > 1) {
						Info<List<String>> info = new Info<List<String>>();
						info.setData(codeList);
						info.setOrigin(IndexFragment_.class);
						openActivity(SpecificShopsActivity_.class, info);

					} else if (codeList != null && codeList.size() == 1) {
						String sId = codeList.get(0);
						Info<String> info = new Info<String>();
						info.setData(sId);
						info.setOrigin(ActivitiesActivity_.class);
						openActivity(ShopInfoActivity.class, info);

					}
				}
			} else if ("checkUpdate".equals(type)) {
				checkUpdate();
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 检查更新版本
	 */
	@Background
	void checkUpdate() {
		if (mlocation == null) {
			return;
		}

		if (!NetWorkCenter.isNetworkConnected(mContext)) {
			showToast("请检查你的网络!");
			return;
		}

		try {
			UserInfo userInfo = mUserModel.getUserInfo();
			CheckUpdateReq checkUpdateReq = new CheckUpdateReq();
			if (userInfo != null) {
				checkUpdateReq.setuId(userInfo.getuId());
				checkUpdateReq.setPwd(userInfo.getPwd());
				checkUpdateReq.setCityName(userInfo.getCity().getCity());
			}
			checkUpdateReq.setDeviceInfo(DeviceUtils.getDeviceInfo(mContext));

			if (mlocation == null) {
				checkUpdateReq.setLat("");
				checkUpdateReq.setLng("");
			} else {
				checkUpdateReq.setLat(mlocation.getLatitude() + "");
				checkUpdateReq.setLng(mlocation.getLongitude() + "");
			}
			checkUpdateReq.setDeviceType("AD_VERSION");
			checkUpdateReq.setVersionCode(Constant.currentVersion);
			CodeResult<CheckUpdateRes> reuslt = mUserModel.checkUpdate(checkUpdateReq);
			showUpdateView(reuslt);
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网路不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网路不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}

	}

	private void showUpdateView(final CodeResult<CheckUpdateRes> reuslt) {
		if (reuslt != null && reuslt.code == 1) {
			mActivity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					CheckUpdateRes checkUpdateRes = reuslt.getBean();
					if (checkUpdateRes != null && checkUpdateRes.getIsUpdate() > 0) {
						CheckUpdateDialog checkDialog = new CheckUpdateDialog();
						checkDialog.Dialog(mContext, checkUpdateRes.getVersionName(),
								(int) (checkUpdateRes.getSize() / 1024) + "M",
								ParseUtils.convertTime(checkUpdateRes.getReleaseTime() * 1000, "yyyy年MM月dd日") + "发布",
								checkUpdateRes.getUpdateInfo().replace("<LF>", "\n"), checkUpdateRes.getDownloadUrl());
					}
				}
			});
		}
	}

	/**
	 * 去掉活动url的问号后面的参数
	 * 
	 * @return
	 */
	public String resetUrl(String url) {
		String[] s = url.split("\\?");
		url = s[0];
		return url;
	}

	public static String GetVersion(Context context) {
		try {
			PackageInfo manager = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return manager.versionName;
		} catch (NameNotFoundException e) {
			return "Unknown";
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!TextUtils.isEmpty(affertName) && affertName.equals(ShopInfoActivity.class.getName())) { // 如果店铺详情过来不处理
			return;
		} else {
			initView();
		}
	}

	protected void obtainInfo() {
		if (getInfoBean() != null && getInfoBean().getOriginClzz().getName().equals(ShopInfoActivity.class.getName())) {
			affertName = getInfoBean().getOriginClzz().getName();
		} else if (getInfoBean() != null && getInfoBean().getData() != null
				&& getInfoBean().getOriginClzz().getName().equals(IndexFragment_.class.getName())) {
			Object obj = getInfoBean().getData();
			affertName = getInfoBean().getOriginClzz().getName();
			if (obj instanceof String) {
				url = obj.toString();
			}
		} else if (getInfoBean() != null && getInfoBean().getData() != null
				&& getInfoBean().getOriginClzz().getName().equals(OrderStatusActivity_.class.getName())) {
			Object obj = getInfoBean().getData();
			affertName = getInfoBean().getOriginClzz().getName();
			if (obj instanceof String) {
				url = obj.toString();
			}
		} else if (getInfoBean() != null && getInfoBean().getData() != null
				&& getInfoBean().getOriginClzz().getName().equals(JPushReceiver_.class.getName())) { // 推送过来的
			Object obj = getInfoBean().getData();
			affertName = getInfoBean().getOriginClzz().getName();
			if (obj instanceof String) {
				url = obj.toString();
			}
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean backOperate() {
		clear();
		Info<Class> info = new Info<Class>(IndexFragment_.class);
		info.setOrigin(ActivitiesActivity_.class);
		openActivity(HomeActivity_.class, info);
		finish();
		return true;
	}

	private void clear() {
		hideInputMethod();
		mWeb = null;
		mContainer.removeAllViews();
	}

	/**
	 * 隐藏输入法
	 */
	public void hideInputMethod() {
		if (mActivity.getCurrentFocus() != null) {
			imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

}
